# -*- coding: utf-8 -*-
# Author: xiantingDeng
# Email: dengxianting@shxgroup.net
# Time: 2020/8/6 18:07


import os
import re
from common.utils.env_util import EnvionMent

apk_path = EnvionMent().get_package_path()


def get_appPackage_activity():
    '''
    自动获取apk包名和activity名
    :param apk_path apk绝对路径
    :return:appPackage, appActivity
    '''
    if os.path.exists(apk_path):
        apkVersion = ""
        appPackage = ""
        appActivity = ""
        cmd_str = r"aapt dump badging {}".format(apk_path)
        try:
            with os.popen(cmd_str, "r") as f:
                out_str = f.buffer.read().decode(encoding='utf8')

                apkVersion = re.search(r"(\d\.){2,}\d", out_str).group()
                appPackage = re.search("package: name='.+' versionCode", out_str).group().replace("package: name='",
                                                                                                  "").replace(
                    "' versionCode", "")
                appActivity = re.search("launchable-activity: name='.+'  label=", out_str).group().replace(
                    "launchable-activity: name='",
                    "").replace("'  label=", "")
                return (apkVersion, appPackage, appActivity)
        except Exception as e:
            return None
    else:
        return None


def get_apk_info():
    '''
    根据apk包名检测当前应用环境
    :return: 测试包时返回test，生产包时返回prod
    '''
    if os.path.exists(apk_path):
        apkVersion, appPackage, appActivity = get_appPackage_activity()
        if "test" in appPackage:
            return ("test", apk_path, apkVersion, appPackage, appActivity)
        else:
            return ("prod", apk_path, apkVersion, appPackage, appActivity)
    else:
        return (None, None, None, None)

if __name__ == "__main__":
    print(get_apk_info())